package com.sykj.fileupload.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class ThreadPoolUtil {
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolUtil.class);
    // 核心参数
    private int corePoolSize = 10;
    private int maximumPoolSize = 15;
    private long keepAliveTime = 3;
    private long timeout = 10;
    private TimeUnit unit = TimeUnit.SECONDS;
    /**
     * 这个队列接收到任务的时候，如果当前线程数小于核心线程数，则新建线程(核心线程)处理任务；
     * 如果当前线程数等于核心线程数，则进入队列等待。
     * 由于这个队列没有最大值限制，即所有超过核心线程数的任务都将被添加到队列中，
     * 这也就导致了maximumPoolSize的设定失效，因为总线程数永远不会超过corePoolSize
     */
    private LinkedBlockingQueue queue = new LinkedBlockingQueue();

    private ThreadPoolExecutor executor = null;
    private static ThreadPoolUtil threadPoolUtil = null;

    /**
     * 单例
     * @return
     */
    public static ThreadPoolUtil init(){
        if(threadPoolUtil == null){
            threadPoolUtil = new ThreadPoolUtil();
        }
        return threadPoolUtil;
    }

    /**
     * 私有构造方法
     */
    private ThreadPoolUtil(){
        executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, queue);
        logger.info("ThreadPool init success");
    }

    /**
     * 获取线程池
     * @return
     */
    public ThreadPoolExecutor getExecutor(){
        return executor;
    }

    /**
     * 放入线程池
     * @param runnable
     */
    public void executor(Runnable runnable){
        getExecutor().execute(runnable);
    }

    /**
     * 放入线程池
     * @param thread
     */
    public void executor(Thread thread){
        getExecutor().execute(thread);
    }

    /**
     * 获取队列线程数
     * @return
     */
    public int getQueueSize(){
        return getExecutor().getQueue().size();
    }

    public void shutdown(){
        getExecutor().shutdown();
        logger.info("ThreadPool shutdown success");
    }
}
